class User < ActiveRecord::Base
  
  has_and_belongs_to_many :roles
  has_one :user_info     
  has_one :user_detail    
  
  validates_presence_of :name,:message =>"姓名不能为空!"  
  validates_presence_of :nickname,:message =>"昵称不能为空!" 
  validates_presence_of :email,:on => :create,:message =>"Email不能为空!" 
  validates_presence_of :password,:on => :create,:message =>"密码不能为空!"  
  validates_presence_of :password_confirmation,:on => :create,:message =>"请重新输入密码!"  
  
  validates_uniqueness_of :name, :message =>"姓名不能重复！" 
  validates_uniqueness_of :email,:on => :create,:message =>"Email不能重复！" 
  validates_confirmation_of :password,:on => :create, :message =>"请两次输入相同的密码!"
  
  validates_format_of :email,:on => :create,:message => "Email不合法!",:with => /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i  
  validates_length_of :password,:password_confirmation, :on => :create,:minimum => 4,:with  => /^((?:[-a-z0-9]+)+)$/i, :message=>"密码要求由英文字母 (a-z大小写)、阿拉伯数字 (0-9) 组成且长度为6-16位字符！"  
  validates_length_of :password,:password_confirmation, :on => :create, :maximum => 16,:with  => /^((?:[-a-z0-9]+)+)$/i, :message=>"密码要求由英文字母 (a-z大小写)、阿拉伯数字 (0-9) 组成且长度为6-16位字符！"  
 
   #def validate
    #errors.add_to_base("Missing password") if hashed_password.blank?
  #end
  
  def self.authenticate(name, password)
    user = self.find_by_name(name)
    if user
      expected_password = encrypted_password(password, user.salt)
      if user.hashed_password != expected_password
        user = nil
      end
    end
    user
  end
  
  def password
    @password
  end
  
  def password= (pwd)
    @password = pwd
    return if pwd.blank?
    create_new_salt
    self.hashed_password = User.encrypted_password(self.password,self.salt)
  end
  
  private
  
  def self.encrypted_password(password, salt)
    string_to_hash = password + "wibble" + salt
    Digest::SHA1.hexdigest(string_to_hash)
  end
  
  def create_new_salt
    self.salt = self.object_id.to_s + rand.to_s
  end
end
